using System;
using UnityEngine;

namespace Gj
{
    [Serializable]
    public struct TerrainItemInfo
    {
        public Vector3 offset;
        public Vector3 info;
        public Vector3 point;
        public int r;
    }

    public class TerrainItem : MonoBehaviour, TerrainElement
    {
        public float radius;
        public TerrainItemInfo[] infos;
        public TerrainMesh[] Meshes;
        public int r;
        public int ori;

        public TerrainMesh[] GetMesh()
        {
            return Meshes;
        }

        public void SetOri(int _r)
        {
            if (_r >= 4) _r -= 4;
            r = _r;
            transform.localRotation = Quaternion.Euler(new Vector3(0, r * 90, 0));
        }

        public void AddOri(int _r)
        {
            SetOri(r + _r);
        }

        public TerrainItemInfo[] getItemInfos()
        {
            return getItemInfos(0);
        }

        public TerrainItemInfo[] getItemInfos(int pr)
        {
            var _r = false;
            var a = r + pr;
            if (a >= 4) a -= 4;
            var _infos = new TerrainItemInfo[infos.Length];
            for (var i = 0; i < infos.Length; i++)
            {
                if (_r) _infos[i].info = new Vector3(infos[i].info.z, 0, infos[i].info.x);
                _infos[i] = FormatItemInfo(a, infos[i]);
            }

            return _infos;
        }

        private TerrainItemInfo FormatItemInfo(int a, TerrainItemInfo itemInfo)
        {
            if (a == 1 || a == 3)
            {
                itemInfo.info = new Vector3(itemInfo.info.z, 0, itemInfo.info.x);
                itemInfo.point = new Vector3(itemInfo.point.z, 0, itemInfo.point.x);
            }

            itemInfo.r += a;
            if (itemInfo.r >= 4) itemInfo.r -= 4;
            switch (itemInfo.r)
            {
                case 0:
                    itemInfo.offset = new Vector3(itemInfo.point.x - itemInfo.info.x, 0,
                        itemInfo.point.z - itemInfo.info.z);
                    break;
                case 1:
                    itemInfo.offset = new Vector3(itemInfo.point.x - itemInfo.info.x, 0, itemInfo.point.z * -1);
                    break;
                case 2:
                    itemInfo.offset = new Vector3(itemInfo.point.x * -1, 0, itemInfo.point.z * -1);
                    break;
                case 3:
                    itemInfo.offset = new Vector3(itemInfo.point.x * -1, 0, itemInfo.point.z - itemInfo.info.z);
                    break;
            }

            return itemInfo;
        }
    }
}